﻿using QxFramework.Core;
using QxFramework.Utilities;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Map :MonoSingleton<Map>
{
    public Dictionary<Vector2Int, MapCell> cellDIC = new Dictionary<Vector2Int, MapCell>();
    [Header("地图大小")]
    public Vector2Int mapSize;
    [Header("基地大小")]
    public Vector2Int baseSize;
    [Header("初始产雷几率")]
    public int probability;
    public Vector2Int clickedCell;
    private List<GameObject> players=new List<GameObject>();
    bool isInitChess;
    void Start()
    {
        isInitChess = false;
        players.Add(this.transform.parent.Find("Player1").gameObject);
        players.Add(this.transform.parent.Find("Player2").gameObject);
        Debug.Log("Init Turn");
        TurnController.Instance.Init();
        AdjustScale();
        InitMap(mapSize, baseSize);
        TurnController.Instance.ChessInit();
        TurnController.Instance.StartTurn(1);
    }

    void Update()
    {
        if (!isInitChess)
        {
            InitChessPos();
            Refresh();
            isInitChess = true;
        }
    }


    /// <summary>
    /// 调整窗体大小
    /// </summary>
    void AdjustScale()
    {
        GridLayoutGroup grid = this.GetComponent<GridLayoutGroup>();
        RectTransform rect = this.GetComponent<RectTransform>();
        rect.sizeDelta=new Vector2(rect.rect.height * mapSize.x / mapSize.y,rect.rect.height);
        rect.anchoredPosition = new Vector2(rect.rect.width / 2, 0);
        grid.cellSize =new Vector2(rect.rect.height / mapSize.y, rect.rect.height / mapSize.y);
   
    }
    /// <summary>
    /// 生成地图，初始化
    /// </summary>
    /// <param name="map"></param>
    /// <param name="bas"></param>
    void InitMap(Vector2Int map, Vector2Int bas)
    {
        GridLayoutGroup grid = this.GetComponent<GridLayoutGroup>();
        int starX = (map.x / 2 - bas.x / 2) - 1;
        for (int i = 0; i < map.y; i++)
        {
            for (int j = 0; j < map.x; j++)
            {
                var t = ResourceManager.Instance.Instantiate("Prefabs/Item/MapCell", this.transform);
                t.name = $"{i},{j}";
                t.transform.Find("Mine").GetComponent<RectTransform>().sizeDelta = grid.cellSize;
                cellDIC.Add(new Vector2Int(j, i), t.GetComponent<MapCell>());
                if (i <= bas.y - 1)
                {
                    if (j > starX && j<= starX + bas.x)
                    {
                        t.GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/Blue");
                        var obj= ResourceManager.Instance.Instantiate("Prefabs/Item/Chess", players[1].transform);
                        cellDIC[new Vector2Int(j, i)].cellState = CellState.Chess;
                        Chess chess = obj.GetComponent<Chess>();
                        chess.Id = TurnController.Instance.player2.myChess.Count + 1;
                        chess.player = TurnController.Instance.player2;
                        chess.Pos = new Vector2Int(j, i);
                        chess.OriPos = new Vector2Int();
                        chess.OriPos = chess.Pos;
                        chess.chessObj = obj;
                        chess.state = ChessState.Flying;
                        chess.Arrive = false;
                        TurnController.Instance.player2.myChess.Add(chess);
                        obj.GetComponent<Image>().sprite= ResourceManager.Instance.Load<Sprite>("Sprites/BChess");
                        t.GetComponent<MapCell>().cellType = CellType.Blue;
                    }
                }
                if (i >= map.y - bas.y)
                {
                    if (j > starX && j <=starX + bas.x)
                    {
                        t.GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/Red");
                        var obj=ResourceManager.Instance.Instantiate("Prefabs/Item/Chess", players[0].transform);
                        obj.GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/RChess");
                        cellDIC[new Vector2Int(j, i)].cellState = CellState.Chess;
                        Chess chess = obj.GetComponent<Chess>();
                        chess.Id = TurnController.Instance.player1.myChess.Count + 1;
                        chess.player = TurnController.Instance.player1;
                        chess.Pos = new Vector2Int(j, i);
                        chess.OriPos = new Vector2Int();
                        chess.OriPos = chess.Pos;
                        chess.chessObj = obj;
                        chess.Arrive = false;
                        chess.state = ChessState.Flying;
                        TurnController.Instance.player1.myChess.Add(chess);
                        t.GetComponent<MapCell>().cellType = CellType.Red;
                        
                    }
                }
                if(t.GetComponent<MapCell>().cellType == CellType.Black)
                {
                    if (Random.Range(0, 100) < probability)
                    {
                        t.GetComponent<MapCell>().cellState = CellState.OriMine;
                    }
                }
            }
        }
        InitMineCount();
    }
    void InitMineCount()
    {
        foreach (var x in cellDIC)
        {
            if (x.Value.cellState == CellState.OriMine)
            {
                AddMine(x.Key);
            }
        }
#if DEBUG
        foreach(var x in cellDIC)
        {
            x.Value.transform.Find("Text").GetComponent<Text>().text +=x.Value.mineCount;
        }
#endif
    }
    void DebugPos()
    {
        foreach(var x in cellDIC)
        {
           Debug.Log($"{x.Key},{x.Value.gameObject.GetComponent<RectTransform>().position}");
        }
    }
    private void InitChessPos()
    {
        foreach(var x in TurnController.Instance.player1.myChess)
        {
            x.transform.position = GetWorldPos(x.Pos);
        }
        foreach (var x in TurnController.Instance.player2.myChess)
        {
            x.transform.position = GetWorldPos(x.Pos);
        }
    }
    /// <summary>
    /// 根据地图坐标获取世界坐标
    /// </summary>
    /// <param name="pos"></param>
    /// <returns></returns>
    public Vector2 GetWorldPos(Vector2Int pos)
    {
        MapCell cell;
        if(cellDIC.TryGetValue(pos,out cell))
        {
            return cell.transform.position;
        }
        else
        {
            Debug.LogError($"坐标超界{pos}");
            return new Vector2(0, 0);
        }
    }
    /// <summary>
    /// 给cell打高光
    /// </summary>
    /// <param name="pos"></param>
    public void HightLightCell(Vector2Int pos)
    {
        if (cellDIC[pos].isDisplay)
        {
            cellDIC[pos].GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/HLWhite");
        }
        else
        {
            switch (cellDIC[pos].cellType)
            {
                case CellType.Black:
                    cellDIC[pos].GetComponent<Image>().sprite= ResourceManager.Instance.Load<Sprite>("Sprites/HLBlack");
                    break;
                case CellType.Blue:
                    cellDIC[pos].GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/HLBlue");
                    break;
                case CellType.Red:
                    cellDIC[pos].GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/HLRed");
                    break;
            }
        }
    }
    /// <summary>
    /// 结束高光
    /// </summary>
    /// <param name="pos"></param>
    public void EndHightLigthCell(Vector2Int pos)
    {
        Sprite sprite = cellDIC[pos].GetComponent<Image>().sprite;
        if (cellDIC[pos].isDisplay)
        {
            sprite = ResourceManager.Instance.Load<Sprite>("Sprites/White");
        }
        else
        {
            switch (cellDIC[pos].cellType)
            {
                case CellType.Black:
                    sprite = ResourceManager.Instance.Load<Sprite>("Sprites/Black");
                    break;
                case CellType.Blue:
                    sprite = ResourceManager.Instance.Load<Sprite>("Sprites/Blue");
                    break;
                case CellType.Red:
                    sprite = ResourceManager.Instance.Load<Sprite>("Sprites/Red");
                    break;
            }
        }
        cellDIC[pos].GetComponent<Image>().sprite=sprite;
    }
    public void Refresh()
    {
        foreach (var x in cellDIC)
        {
            Text text = x.Value.transform.Find("Text").GetComponent<Text>();
            Image image = x.Value.transform.Find("Mine").GetComponent<Image>();
            text.text = default;
            if (x.Value.isDisplay)
            {
                if (x.Value.cellType == CellType.Black)
                {
                    x.Value.GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/White");
                }
                switch (x.Value.cellState) 
                {
                    case CellState.OriMine:
                        image.gameObject.SetActive(true);
                        image.sprite = ResourceManager.Instance.Load<Sprite>("Sprites/OriMine");
                        break;
                    case CellState.RMine:
                        image.gameObject.SetActive(true);
                        image.sprite = ResourceManager.Instance.Load<Sprite>("Sprites/RMine");
                        break;
                    case CellState.BMine:
                        image.gameObject.SetActive(true);
                        image.sprite = ResourceManager.Instance.Load<Sprite>("Sprites/BMine");
                        break;
                    case CellState.Null:
                        image.gameObject.SetActive(false);
                        break;
                }


                text.text += x.Value.mineCount.ToString();
                switch (x.Value.mineCount)
                {
                    case 0:
                        text.text = default;
                        break;
                    case 1:
                        text.color = new Color32(255, 0, 0,255);
                        break;
                    case 2:
                        text.color = new Color32(0, 128, 0,255);
                        break;
                    case 3:
                        text.color = new Color32(0, 0, 255, 255);
                        break;
                    case 4:
                        text.color = new Color32(128, 0, 0, 255);
                        break;
                    case 5:
                        text.color = new Color32(0, 0, 128, 255);
                        break;
                    case 6:
                        text.color = new Color32(128, 128, 0, 255);
                        break;
                    case 7:
                        text.color = new Color32(0, 0, 0, 255);
                        break;
                    case 8:
                        text.color = new Color32(128, 128, 128, 255);
                        break;
                    case 9:
                        text.color = Color.black;
                        break;
                }
            }
            else
            {
                if (x.Value.cellType == CellType.Black)
                {
                    x.Value.GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>("Sprites/Black");
                }
                text = default;
                image.gameObject.SetActive(false);
            }
        }
    }
    /// <summary>
    /// 给周围一圈加雷数，传雷的坐标
    /// </summary>
    /// <param name="pos"></param>
    public void AddMine(Vector2Int pos)
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                MapCell cell;
                if (cellDIC.TryGetValue(pos - new Vector2Int(1, 1) + new Vector2Int(i, j), out cell))
                {
                    cell.mineCount++;
                }
            }
        }
    }
    public void RemoveMine(Vector2Int pos)
    {
        cellDIC[pos].cellState = CellState.Null;
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                MapCell cell;
                if (cellDIC.TryGetValue(pos - new Vector2Int(1, 1) + new Vector2Int(i, j), out cell))
                {
                    if (cell.mineCount == 0) break;
                    cell.mineCount--;
                }
            }
        }
    }

            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
    }

